package com.example.roomjavademo.database;

import android.content.Context;

import androidx.annotation.NonNull;
import androidx.room.Database;
import androidx.room.Room;
import androidx.room.RoomDatabase;
import androidx.room.migration.Migration;
import androidx.sqlite.db.SupportSQLiteDatabase;

import com.example.roomjavademo.dao.UserDao;
import com.example.roomjavademo.entity.UserBean;


@Database(
        entities = {UserBean.class},
        version = 4
)
public abstract class DatabaseHelper extends RoomDatabase {

    public abstract UserDao getUserDao();

    private static DatabaseHelper mDatabaseHelper;

    public static synchronized DatabaseHelper getDataBase(Context context) {
        if (mDatabaseHelper == null) {
            mDatabaseHelper = Room.databaseBuilder(context.getApplicationContext(), DatabaseHelper.class, "user")
//                    .fallbackToDestructiveMigration()
//                    .addMigrations(migration2_3)
                    .addMigrations(migration3_4)
                    .build();
        }
        return mDatabaseHelper;
    }

    static final Migration migration2_3 = new Migration(2, 3) {
        @Override
        public void migrate(@NonNull SupportSQLiteDatabase database) {
            database.execSQL("ALTER TABLE user ADD COLUMN sex char(11) ");
        }
    };
    static final Migration migration3_4 = new Migration(3, 4) {
        @Override
        public void migrate(@NonNull SupportSQLiteDatabase database) {
            //先创建一个临时表
            database.execSQL("CREATE TABLE user_temp(uid INTEGER PRIMARY KEY  AUTOINCREMENT," +
                    "last_name TEXT,age INTEGER NOT NULL,sex TEXT )");
            //将旧的表中的数据迁移过来
            database.execSQL("INSERT INTO user_temp (uid,last_name,age,sex) SELECT uid,last_name,age,sex FROM user ");
            //将旧的表删除
            database.execSQL("DROP TABLE user");
            //将临时表改名
            database.execSQL("ALTER TABLE user_temp RENAME to user");
        }
    };
}